<template>
  <div>
    <h2 style="margin-bottom:15px">小区管理</h2>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="省">
        <el-popover placement="top" width="160" trigger="focus" v-model="popoverProvinceVisible">
          <p>请先选择省</p>
          <el-select
            slot="reference"
            @change="fetchCities"
            v-model="queryForm.province"
            placeholder="请选择省"
          >
            <el-option
              v-for="item in provinces"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-popover>
      </el-form-item>
      <el-form-item label="市">
        <el-popover placement="top" width="160" trigger="focus" v-model="popoverCityVisible">
          <p>请先选择市</p>
          <el-select
            slot="reference"
            @change="fetchAreas"
            v-model="queryForm.city"
            placeholder="请选择市"
          >
            <el-option
              v-for="item in cities"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-popover>
      </el-form-item>
      <el-form-item label="区域">
        <el-popover placement="top" width="160" trigger="focus" v-model="popoverAreaVisible">
          <p>请先选择区域</p>
          <el-select slot="reference" v-model="queryForm.area" placeholder="请选择区域">
            <el-option
              v-for="item in areas"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-popover>
      </el-form-item>
      <el-form-item label="小区名称">
        <el-input v-model="queryForm.name" placeholder="请输入小区名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="info" @click="onReset">重置</el-button>
        <el-button type="danger" @click="onBatchDelete">批量删除</el-button>
        <el-button type="success" @click="onAdd">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-if="tableData.length > 0"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="小区名称"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="area" label="区域名称"></el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.image" alt="小区图片" style="width: 40px; height: 40px;" />
        </template>
      </el-table-column>
      <el-table-column prop="parkingSpaces" label="停车位数量"></el-table-column>
      <el-table-column prop="remarks" label="备注"></el-table-column>
      <el-table-column label="操作" width="270">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" type="primary" @click="onEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="onDelete(scope.row)">删除</el-button>
            <el-button size="mini" @click="onBatchAdd(scope.row)">套房批量添加</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <div v-else style="text-align: center; margin-top: 20px;">
      <el-empty description="暂无数据，请先进行查询"></el-empty>
    </div>

    <el-dialog title="添加小区" :visible.sync="addDialogVisible">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="区域名称" prop="area">
          <el-input v-model="addForm.area" disabled></el-input>
        </el-form-item>
        <el-form-item label="小区名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入小区名称"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="停车位数量" prop="parkingSpaces">
          <el-input v-model="addForm.parkingSpaces" placeholder="请输入停车位数量"></el-input>
        </el-form-item>
        <el-form-item label="物业电话" prop="propertyPhone">
          <el-input v-model="addForm.propertyPhone" placeholder="请输入物业电话"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <br />
          <el-upload
            class="upload-demo"
            action="/public-rental-housing-ssm/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改小区" :visible.sync="editDialogVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="区域名称" prop="area">
          <el-input v-model="editForm.area" disabled></el-input>
        </el-form-item>
        <el-form-item label="小区名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入小区名称"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="停车位数量" prop="parkingSpaces">
          <el-input v-model="editForm.parkingSpaces" placeholder="请输入停车位数量"></el-input>
        </el-form-item>
        <el-form-item label="物业电话" prop="propertyPhone">
          <el-input v-model="editForm.propertyPhone" placeholder="请输入物业电话"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <br />
          <el-upload
            class="upload-demo"
            action="/public-rental-housing-ssm/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="editHandleUploadSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" :z-index="3000">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onUpdate">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量添加套房" :visible.sync="apartmentDialogVisible" width="500px">
      <el-form :model="apartmentForm" :rules="addRules" ref="apartmentForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始栋" prop="startBuilding">
              <el-input v-model="apartmentForm.startBuilding"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束栋" prop="endBuilding">
              <el-input v-model="apartmentForm.endBuilding"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始楼梯口" prop="startStaircase">
              <el-input v-model="apartmentForm.startStaircase"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束楼梯口" prop="endStaircase">
              <el-input v-model="apartmentForm.endStaircase"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始楼层" prop="startFloor">
              <el-input v-model="apartmentForm.startFloor"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束楼层" prop="endFloor">
              <el-input v-model="apartmentForm.endFloor"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积 (平方米)" prop="area">
              <el-input v-model="apartmentForm.area"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="月租金 (元)" prop="rent">
              <el-input v-model="apartmentForm.rent"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一梯几户" prop="unitsPerStaircase">
              <el-select v-model="apartmentForm.unitsPerStaircase">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
                <el-option label="3" value="3"></el-option>
                <el-option label="4" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="房间个数" prop="rooms">
              <el-select v-model="apartmentForm.rooms">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
                <el-option label="3" value="3"></el-option>
                <el-option label="4" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="卫生间个数" prop="bathrooms">
              <el-select v-model="apartmentForm.bathrooms">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
                <el-option label="3" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="大厅个数" prop="halls">
              <el-select v-model="apartmentForm.halls">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="阳台个数" prop="balconies">
              <el-select v-model="apartmentForm.balconies">
                <el-option label="1" value="1"></el-option>
                <el-option label="2" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="apartmentForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="apartmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApartmentForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      queryForm: {
        province: "",
        city: "",
        area: "",
        name: ""
      },
      tableData: [],
      provinces: [],
      cities: [],
      areas: [],
      apartmentDialogVisible: false,
      editDialogVisible: false,
      popoverProvinceVisible: false,
      popoverCityVisible: false,
      popoverAreaVisible: false,
      dialogVisible: false,
      addDialogVisible: false,
      addForm: {
        area: "",
        name: "",
        address: "",
        parkingSpaces: "",
        propertyPhone: "",
        image: "",
        parkingSpaces: "",
        remarks: ""
      },
      apartmentForm: {
        areaName: "",
        community: "",
        startBuilding: "",
        endBuilding: "",
        startStaircase: "",
        endStaircase: "",
        startFloor: "",
        endFloor: "",
        area: "",
        rent: "",
        unitsPerStaircase: "",
        rooms: "",
        bathrooms: "",
        halls: "",
        balconies: "",
        remark: ""
      },
      editForm: {},
      fileList: [],
      dialogImageUrl: "",
      currentPage: 1,
      pageSize: 5,
      total: "",
      rules: {
        area: [
          { required: true, message: "区域名称不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入小区名称", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
            message: "小区名称只能包含中文或英文字符",
            trigger: "blur"
          }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        parkingSpaces: [
          { required: true, message: "请输入停车位数量", trigger: "blur" },
          {
            pattern: /^[0-9]+$/,
            message: "停车位数量只能包含数字",
            trigger: "blur"
          }
        ],
        propertyPhone: [
          { required: true, message: "请输入物业电话", trigger: "blur" },
          {
            pattern: /^[0-9-]+$/,
            message: "物业电话只能包含数字和横杠",
            trigger: "blur"
          }
        ],
        image: [{ required: true, message: "请上传图片", trigger: "change" }]
      },
      addRules: {
        startBuilding: [
          { required: true, message: "请输入开始栋", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        endBuilding: [
          { required: true, message: "请输入结束栋", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        startStaircase: [
          { required: true, message: "请输入开始楼梯口", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        endStaircase: [
          { required: true, message: "请输入结束楼梯口", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        startFloor: [
          { required: true, message: "请输入开始楼层", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        endFloor: [
          { required: true, message: "请输入结束楼层", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        area: [
          { required: true, message: "请输入面积", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        rent: [
          { required: true, message: "请输入月租金", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "必须是数字", trigger: "blur" }
        ],
        unitsPerStaircase: [
          { required: true, message: "请选择一梯几户", trigger: "change" }
        ],
        rooms: [
          { required: true, message: "请选择房间个数", trigger: "change" }
        ],
        bathrooms: [
          { required: true, message: "请选择卫生间个数", trigger: "change" }
        ],
        halls: [
          { required: true, message: "请选择大厅个数", trigger: "change" }
        ],
        balconies: [
          { required: true, message: "请选择阳台个数", trigger: "change" }
        ]
      },
      selectedRows: []
    };
  },
  mounted() {
    this.fetchProvinces();
    this.confirmSearch();
  },
  methods: {
    onSearch() {
      if (!this.queryForm.province) {
        this.popoverProvinceVisible = true;
      } else if (!this.queryForm.city) {
        this.popoverCityVisible = true;
      } else if (!this.queryForm.area) {
        this.popoverAreaVisible = true;
      } else {
        this.confirmSearch();
      }
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.confirmSearch();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.confirmSearch();
    },
    confirmSearch() {
      let curr =
        this.queryForm.name == "" ? (this.currentPage - 1) * this.pageSize : 0;
      this.$axios
        .post("community/get", {
          ...this.queryForm,
          size: this.pageSize,
          curr
        })
        .then(res => {
          this.tableData = res.data.data;
          this.total = res.data.total;
          this.$message.success("查询成功");
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    onReset() {
      this.queryForm = {
        province: "",
        city: "",
        area: "",
        communityName: ""
      };
    },
    onEdit(row) {
      this.editDialogVisible = true;
      this.editForm = { ...row };
      this.fileList = [{ name: row.image.split("/").pop(), url: row.image }];
      this.editForm.image = row.image.replace(
        "http://119.91.209.28:18008/public-rental-housing-ssm",
        ""
      );
    },
    onDelete(row) {
      this.$confirm("确定删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("community/delete", [row])
            .then(res => {
              if (res.data.code === 200) {
                this.$message.info(res.data.message);
                this.confirmSearch();
              }
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    onBatchAdd(row) {
      this.apartmentDialogVisible = true;
      this.apartmentForm.areaName = row.area;
      this.apartmentForm.community = row.name;
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    onBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.error("请选择要删除的小区");
        return;
      }
      this.$confirm("确定删除选中的小区吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("community/delete", this.selectedRows)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.info(res.data.message);
                this.confirmSearch();
              }
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    onAdd() {
      if (this.queryForm.area === "") {
        this.$message.error("请查询后再添加");
        return;
      }
      this.addForm = {};
      this.fileList = [];
      this.addForm.area = this.queryForm.area;
      this.addDialogVisible = true;
    },
    onSave() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$axios
            .post("community/add", this.addForm)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success("添加成功");
                this.addDialogVisible = false;
                this.onSearch();
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          this.$message.error("请检查输入");
          return false;
        }
      });
    },
    onUpdate() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确定修改吗？", "提示", {
            type: "warning"
          })
            .then(() => {
              this.$axios
                .post("community/update", this.editForm)
                .then(res => {
                  if (res.data.code === 200) {
                    this.$message.success("修改成功");
                    this.confirmSearch();
                    this.editDialogVisible = false;
                  } else {
                    this.$message.error(res.data.message);
                  }
                })
                .catch(err => {
                  this.$message.error(err.message);
                });
            })
            .catch(() => {});
        } else {
          this.$message.error("请检查输入");
          return false;
        }
      });
    },
    fetchProvinces() {
      this.$axios.post("area/province", { none: "none" }).then(res => {
        if (res.data.code === 200) {
          this.provinces = [];
          res.data.data.forEach(province => {
            this.provinces.push({ value: province.name, label: province.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    fetchCities() {
      this.queryForm.city = "";
      this.$axios
        .post("area/city", { province: this.queryForm.province })
        .then(res => {
          if (res.data.code === 200) {
            this.cities = [];
            res.data.data.forEach(city => {
              this.cities.push({ value: city.name, label: city.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    fetchAreas() {
      this.queryForm.area = "";
      this.$axios
        .post("area/query", {
          province: this.queryForm.province,
          city: this.queryForm.city,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.areas = [];
            res.data.data.forEach(area => {
              this.areas.push({ value: area.name, label: area.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    handleRemove(file, fileList) {
      this.$message.info("已移除图片");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt500KB = file.size / 1024 < 500;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt500KB) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isJPG && isLt500KB;
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片");
    },
    handleUploadSuccess(response, file, fileList) {
      this.addForm.image = response;
    },
    editHandleUploadSuccess(response, file, fileList) {
      this.editForm.image = response;
    },
    submitApartmentForm() {
      this.$refs.apartmentForm.validate(valid => {
        if (valid) {
          this.$axios
            .post("apartment/confirmAdd", this.apartmentForm)
            .then(res => {
              if (res.data.code === 200) {
                this.$confirm(
                  `将添加如下一共${res.data.total}套套房，是否继续？${res.data.data}`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  }
                )
                  .then(() => {
                    this.$axios
                      .post("apartment/add", this.apartmentForm)
                      .then(res => {
                        if (res.data.code === 200) {
                          this.$message.success("批量添加套房成功");
                          this.apartmentDialogVisible = false;
                        } else {
                          this.$message.error(res.data.message);
                        }
                      })
                      .catch(err => {
                        this.$message.error(err.message);
                      });
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消添加"
                    });
                  });
              } else if (res.data.code === 500) {
                this.$alert(
                  `以下套房重复，添加失败，请返回修改。[${res.data.data}]`,
                  "错误",
                  {
                    type: "error"
                  }
                ).catch(() => {});
              }
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
  
  <style scoped>
.demo-form-inline .el-form-item {
  margin-right: 20px;
}
.el-overlay {
  z-index: 1000 !important;
}
</style>
  